/*
 *  NFCSigning - Open source library for signing/validation of NDEF messages
 *  Copyright (C) 2009-2010 The NFCSigning Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */
package org.nfcsigning.algorithm;

import org.nfcsigning.bc.crypto.signers.PKCS1Signer;
import java.io.IOException;
import org.bouncycastle.asn1.x509.RSAPublicKeyStructure;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;

/**
 *
 * @author Markus Kilås
 */
public class RsaSsaPkcs1v15BcVerifier implements SignatureVerifier {

    private static RsaSsaPkcs1v15BcVerifier instance;
    
    public static RsaSsaPkcs1v15BcVerifier getInstance() {
        if(instance == null) {
            instance = new RsaSsaPkcs1v15BcVerifier();
        }
        return instance;
    }
    
    public boolean verifySignature(byte[] signature, byte[] coveredBytes, PublicKey key) throws SignatureException {
        
        try {
            SubjectPublicKeyInfo pkInfo = key.getSubjectPublicKeyInfo();
            RSAPublicKeyStructure pubKey = RSAPublicKeyStructure.getInstance(pkInfo.getPublicKey());
            
            RSAKeyParameters pubParameters = new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
            
            AsymmetricBlockCipher rsaEngine = new RSAEngine();
            rsaEngine.init(false, pubParameters);

            Digest digest = DigestFactory.getDigest("SHA-1");

            PKCS1Signer signer = new PKCS1Signer(rsaEngine, digest);
            
            signer.init(false, pubParameters);
            signer.update(coveredBytes, 0, coveredBytes.length);

            return signer.verifySignature(signature);
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException("IOException: " + ex.getMessage());
        }
    }

}
